package poi_export;

import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.junit.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yujiafan
 * @version 1.0.0
 * @create 2023-01-05
 */
public class WordTest {

    @Test
    public void testInsertText() throws Exception {
        //获取时间
        Calendar cal = Calendar.getInstance();
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH) + 1;
        int year = cal.get(Calendar.YEAR);
        int dow = cal.get(Calendar.DAY_OF_WEEK);
        int dom = cal.get(Calendar.DAY_OF_MONTH);
        int doy = cal.get(Calendar.DAY_OF_YEAR);

        //要替换的map，key为占位符，value为要被替换的值
        Map<String, Object> map = new HashMap<>();
        map.put("${company}", "金马投资公司");
        map.put("${name}", "陈玉");
        map.put("${idNumber}", "642152152542151254");
        map.put("${phone}", "13358445878");
        map.put("${address}", "北京市顺义区张家巷14号");
        map.put("${year}", year);
        map.put("${month}", month);
        map.put("${day}", day);
        map.put("${agent}", "张律师");

        //读取文件
        OPCPackage opcPackage = POIXMLDocument.openPackage("D:\\期货委托合同.docx");
        //加载文档
        XWPFDocument doc = new XWPFDocument(opcPackage);
        //获取所有段落
        List<XWPFParagraph> paragraphList = doc.getParagraphs();
        for (XWPFParagraph par : paragraphList) {
            //获取段落的文本对象
            List<XWPFRun> runs = par.getRuns();
            for (XWPFRun run : runs) {
                //获取文本的值
                String text = run.getText(0);
                //遍历map
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    //获取map的key
                    String key = entry.getKey();
                    //判断文本的值和map的key，文本中是否有和key一样的占位符
                    if (text.indexOf(key) != -1) {
                        //获取对应key的value
                        Object value = entry.getValue();
                        //把文本的内容，key替换为value
                        text = text.replace(key, value.toString());
                        //把替换好的文本内容，保存到当前这个文本对象
                        run.setText(text, 0);
                    }
                }

            }
        }
        File file = new File("D:\\期货委托合同1.docx");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        doc.write(fileOutputStream);
        fileOutputStream.close();
    }

}
